package com.jin.webvideo.js.loadClass;

import com.alibaba.fastjson.JSONObject;
import com.jin.webvideo.js.stopwatch.StopwatchThread;
import com.jin.webvideo.util.sys.ClientUtil;
import com.jin.webvideo.util.base.MapBuilder;
import com.jin.webvideo.util.base.URLUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.entity.StringEntity;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class HttpSender {
    protected static final Logger logger = LoggerFactory.getLogger(HttpSender.class);
    private static final RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();;

    public static String get(String url, String header){
        MapBuilder<String,Object> builder = new MapBuilder<>();
        try {
            InputStream inputStream = ClientUtil.httpGet(url, URLUtil.query2Map(header), config);
            String content = ClientUtil.toString(inputStream);
            inputStream.close();
            builder.put("code", 1).put("msg", "success").put("data", content);
        } catch (IOException e) {
            builder.put("code", 0).put("msg", e.getMessage());
        }
        String result = JSONObject.toJSONString(builder.build());
        logger.debug("complete the get request uri={} header={} result={}", url, header, result);
        return result;
    }

    public static String post(String url, String header, String data) {
        MapBuilder<String,Object> builder = new MapBuilder<>();
        Map<String, String> h = URLUtil.query2Map(header);
        try {
            InputStream inputStream = ClientUtil.httpPost(url, h, new StringEntity(data), null);
            String rst = ClientUtil.toString(inputStream);
            if (inputStream != null){
                inputStream.close();
            }
            builder.put("code", 1).put("msg", "success").put("data", rst);
        } catch (IOException e) {
            builder.put("code", 0).put("msg", e.getMessage());
        }
        String result = JSONObject.toJSONString(builder.build());
        logger.debug("complete the post request uri={} header={} data={} result={}", url, header, data, result);
        return result;
    }

    public static DocElement getDoc(String url, String header) {
        Map<String, String> h = URLUtil.query2Map(header);
        Document document = null;
        try {
            String content = ClientUtil.httpGet(url, h);
            document = Jsoup.parse(content);
            logger.debug("complete the getdoc request uri={} header={} doc={}", url, header, document);
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("failed the getdoc request uri={} header={} error={}", url, header, e);
        }
        return new DocElement(document);
    }
}
